import axios from "axios";
import { message } from "ant-design-vue";
import Cookies from "../utils/cookie";

const http = axios.create({
  baseURL: "/",
  // baseURL: import.meta.env.VITE_APP_API_BASE_URL,
  timeout: 1000 * 180,
  withCredentials: true,
  transformResponse: [
    function (data) {
      try {
        return JSON.parse(data);
      } catch (err) {
        return data;
      }
    },
  ],
  paramsSerializer: function (params) {
    const keys = Object.keys(params);
    const arr = [] as any;
    keys.forEach((item) => {
      if (Array.isArray(params[item])) {
        const url = params[item].map((_: any) => `${item}=${_}`).join("&");
        arr.push(url);
      } else {
        arr.push(`${item}=${params[item]}`);
      }
    });
    const result = arr.join("&");
    return `${result}`;
  },
});

http.interceptors.request.use(
  (config) => {
    // @ts-ignore
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    config.headers!.Authorization = "Bearer " + Cookies.get("Authorization");
    // 防止缓存，GET请求默认带_t参数
    if (config.method === "get") {
      config.params = {
        ...config.params,
        ...{ _t: new Date().getTime() },
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  (response) => {
    if (response.data.code === 300 || response.data.code === 400) {
      message.warning(response.data.msg);
    }
    if (response.data.code === 401) {
      message.warning("token已过期，请重新登录");
      Cookies.clear("Authorization");
      setTimeout(() => {
        window.location.replace(window.location.origin);
      }, 300);
      return Promise.reject(response.data.msg);
    }
    if (response.data.code === 500) {
      message.warning("服务器异常！");
      // return Promise.reject(response.data.msg);
    }
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          message.warning("token已过期，请重新登录");
          Cookies.clear("Authorization");
          break;
        case 500:
          message.warning("服务器异常！");
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default http;
